package logic

import (
	"context"
	"fmt"
	"tb/cache"
	"tb/models/mysql"

	"tb/tbrpc/internal/svc"
	"tb/tbrpc/tbrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *tbrpc.CartAddRequest) (*tbrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	var product mysql.Product

	if err := product.FindProductById(mysql.DB, in.ProductId); err != nil {
		return nil, fmt.Errorf("商品不存在")
	}

	key := fmt.Sprintf("cart:%d:%d", in.UserId, in.ProductId)
	result, _ := cache.Rdb.Exists(l.ctx, key).Result()
	if in.Number > int64(product.Number) {
		return nil, fmt.Errorf("库存不足")
	}
	if result == 0 {
		m := map[string]interface{}{
			"userId":    in.UserId,
			"productId": in.ProductId,
			"number":    in.Number,
		}
		cache.Rdb.HMSet(l.ctx, key, m)
	} else {
		cache.Rdb.HIncrBy(l.ctx, key, "number", in.Number)
	}

	return &tbrpc.CartAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
